<template>
  <BaseMainSlot ref="BaseMainSlot">
    <template v-slot:searchbox v-if="topitemtypeId==='CONFIG'">
      <div class="seach-box">
        <div class="select-box-content">
          <div class="select-box-content-name">设备名称：</div>
          <el-input
            v-model="equipmentName"
            clearable
            placeholder="请输入设备名称"
            @change="query()"
          />
        </div>
        <div class="select-box-content">
          <div class="select-box-content-name">设备类型：</div>
          <el-cascader
            v-model="equipmentTypeCode"
            :props="defaultProps"
            :options="equipmentTypeList"
            :show-all-levels="false"
            clearable
            placeholder="请选择所属设备类型"
            @change="query()"
          />
        </div>
      </div>
    </template>
    <template v-slot:typenodeslot>
      <SelectButton
        :topitem-select-list="topitemSelectList"
        @topitemtype="topitemtype"
      />
    </template>
    <template v-slot:content>
      <div class="check-item-con">
        <div v-if="topitemtypeId==='CONFIG'" class="tr-sid">
          <div class="sid-head">设备列表</div>
          <div class="sid-tree">
            <Equiplist ref="Equiplist" @selectionChange="selectionChange" />
          </div>
        </div>
        <div :class="topitemtypeId==='CONFIG'?'table-box':'table-box-all'">
          <ActionBar
            :add-active="addActive"
            :del-active="delActive"
            :page-no="152"
            @add="add"
            @del="del"
          />
          <e-table
            ref="tableData"
            rowKey="checkItemModelId"
            :table-data="tableData"
            :table-columns="tableColumnsData"
            :page="currentPage"
            :size="pageSize"
            :total="totalSize"
            :loading="loading"
            :table-option="tableOption"
            :loadSaveColumnWhenTableChange="loadSavedColumns"
            @sizeChange="changePageSize"
            :table-column-sum="topitemtypeId"
            @pageChange="changeCurrentPage"
            @tableUpdatePlus="mixTableUpdatePlus"
            @handleSelectionChange="handleSelectionChange"
          >
            <template
              v-if="scoped.row.checkItemModelId"
              slot="standardValue"
              slot-scope="scoped"
            >
              <div
                v-if="scoped.row.checkType==='NUMTYPE'"
              >{{ scoped.row.lowerLimit?'下限:'+scoped.row.lowerLimit+scoped.row.unitName:'' }}{{ scoped.row.upperLimit?'上限:'+scoped.row.upperLimit+scoped.row.unitName:'' }}</div>
              <div v-else>{{ scoped.row.standardValue||'--' }}</div>
            </template>

            <template
              v-if="scoped.row.checkItemModelId"
              slot="checkType"
              slot-scope="scoped"
            >{{ changeCheckType(scoped.row.checkType) }}</template>

            <template slot-scope="scoped" slot="unitName">
              <div
                v-if="scoped.row.checkType==='NUMTYPE'&&scoped.row.unitName"
              >{{ scoped.row.unitName }}</div>
              <div
                v-if="scoped.row.checkType==='ENUMTYPE'&&scoped.row.enumContent"
              >{{ scoped.row.enumContent }}</div>
            </template>

            <template
              slot="operate"
              v-if="scoped.row.checkItemModelId"
              slot-scope="scoped"
            >
              <span
                v-if="judgePermission(152,'editTem')"
                class="table-btns-box"
                @click="edit(scoped.row)"
              >
                <i class="el-icon-edit-outline"></i>
                <span>修改</span>
              </span>

              <span
                v-if="judgePermission(152,'deleteoneTem')"
                class="table-btns-box table_del_btn"
                @click="delOne(scoped.row)"
              >
                <i class="el-icon-delete table_del_btn"></i>
                <span>删除</span>
              </span>
            </template>
          </e-table>
        </div>
      </div>
      <AddEditConfigDialog
        ref="addEditConfigDialog"
        :now-equip-object="nowEquipObject"
        :now-chance-stau="nowChanceStau"
        :title-text="titleText"
        :edit-object="editObject"
        :show.sync="showAddEditConfigDialog"
        @closeDialog="closeDialog"
        @cancelDialog="cancel"
      />
      <AddEditTemplateDialog
        ref="addEditTemplateDialog"
        :now-chance-stau="nowChanceStau"
        :title-text="titleText"
        :edit-object="editObject"
        :show.sync="showAddEditTemplateDialog"
        @closeDialog="closeDialog"
        @cancelDialog="cancel"
      />
    </template>
  </BaseMainSlot>
</template>

<script>
import ActionBar from "@/components/ActionBar";
import Pagination from "@/components/Pagination";
import maintenanceDataitemApi from "@/api/equip-maintenance-manage/maintenance-dataitem";
import BaseMainSlot from "@/components/BaseMainSlot/kong-new.vue";
import AddEditConfigDialog from "./components/add-edit-config-dialog.vue";
import AddEditTemplateDialog from "./components/add-edit-template-dialog.vue";
import { mymixin } from "@/utils/mixin";
import SelectButton from "@/components/equipTypeSelectButton/selcetButton.vue";
import equipTypeApi from "@/api/equip-manage/equip-type/index";
import Equiplist from "@/components/EquipList/equiplist-much.vue";
import { mapGetters } from "vuex";
export default {
  name: "MaintenanceDataitem",
  components: {
    ActionBar,
    Pagination,
    BaseMainSlot,
    AddEditConfigDialog,
    AddEditTemplateDialog,
    SelectButton,
    Equiplist,
  },
  mixins: [mymixin],
  data() {
    return {
      loadSavedColumns: true,
      // 控制弹出框显示隐藏
      showAddEditConfigDialog: false,
      // 控制弹出框显示隐藏
      showAddEditTemplateDialog: false,
      //  搜索条件:设备类型
      equipmentTypeCode: "",
      //  搜索条件:设备名称
      equipmentName: "",
      defaultProps: {
        children: "childList",
        value: "equipmentTypeCode",
        label: "equipmentTypeName",
        emitPath: false,
        checkStrictly: true,
      },
      // 关联设备类型
      equipmentTypeList: [],
      checkedIdList: [],
      topitemtypeId: "CONFIG",
      tableData: [],
      checkTypeList: [
        { id: "TEXTTYPE", name: "文本型" },
        { id: "ENUMTYPE", name: "列表型" },
        { id: "BOOLEANTYPE", name: "是否型" },
        { id: "NUMTYPE", name: "数字型" },
      ],
      // 选中的设备
      nowEquipObject: {},
      topitemSelectList: [
        { id: "CONFIG", name: "设备保养项配置" },
        { id: "TEMPLATE", name: "保养项模板配置" },
      ],
      // 设备保养配置表单展示项
      tableLabel_Config: [
        {
          label: "保养内容",
          param: "checkItemContent",
          show: true,
        },
        {
          label: "保养项名称",
          param: "checkItemName",
          show: true,
        },
        // {
        //   label: "标准值",
        //   param: "standardValue",
        //   slotName: "standardValue",
        //   notSearch: true,
        //   show: true,
        // },
        // {
        //   label: "保养方式",
        //   param: "accessMethod",
        //   show: true,
        // },
      ],
      // 保养项配置表单展示项
      tableLabel_Temp: [
        {
          label: "保养项模板名称",
          param: "checkItemName",
          show: true,
        },
        // {
        //   label: "保养项类型",
        //   param: "checkType",
        //   slotName: "checkType",
        //   show: true,
        //   type: "Select", // input Select Checkbox date
        //   typeObj: {
        //     // 动态数据和静态数据
        //     list: [
        //       { id: "TEXTTYPE", name: "文本型" },
        //       { id: "ENUMTYPE", name: "列表型" },
        //       { id: "BOOLEANTYPE", name: "是否型" },
        //       { id: "NUMTYPE", name: "数字型" },
        //     ],
        //     listName: ["name", "id"], // 动态数据和静态数据数组字段名
        //   },
        // },
        {
          label: "保养方式",
          param: "accessMethod",
          show: true,
        },
        // {
        //   label: "单位/选项名称",
        //   param: "unitName",
        //   slotName: "unitName",
        //   notSearch: true,
        //   show: true,
        // },
      ],

      tableColumnsData: [
        {
          label: "保养内容",
          param: "checkItemContent",
          show: true,
        },
        {
          label: "保养项名称",
          param: "checkItemName",
          show: true,
        },
        // {
        //   label: "标准值",
        //   param: "standardValue",
        //   slotName: "standardValue",
        //   notSearch: true,
        //   show: true,
        // },
        {
          label: "保养方式",
          param: "accessMethod",
          show: true,
        },
      ],
      // 表单事件
      tableOption: {
        label: "操作",
        options: [
          {
            label: "操作",
            slotName: "operate",
          },
        ],
      },
      bFirstLoad: true,
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission",
    }),
  },
  watch: {},
  created() {
    this.queryEquipmentType();
  },
  mounted() {},
  methods: {
    query() {
      this.$refs.Equiplist.query(this.equipmentName, this.equipmentTypeCode);
    },
    // 选择设备传出选择的该设备信息
    selectionChange(e) {
      this.nowEquipObject = e;
      this.queryConfigPageList();
    },
    // 保养项类型转换成名字
    changeCheckType(v) {
      var index = this.checkTypeList.findIndex((item) => item.id === v);
      if (index !== -1) {
        return this.checkTypeList[index]["name"];
      }
    },
    // 关联设备类型
    queryEquipmentType() {
      this.loading = false;
      // 获取数据
      let param = {};
      equipTypeApi.queryTree(param).then((res) => {
        this.loading = false;
        if (res.code === 1) {
          let data = res.data || [];
          this.equipmentTypeList = data;
          this.filterTreeKey(
            this.equipmentTypeList,
            this.defaultProps.children
          );
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    // 获取点击的分页index
    topitemtype(e) {
      this.topitemtypeId = e;
      this.pageSize = 10;
      this.currentPage = 1;
      this.checkedIdList = [];

      if (this.topitemtypeId === "CONFIG") {
        if (!this.bFirstLoad) this.tableColumnsData = this.tableLabel_Config;
        this.$nextTick(() => {
          this.$refs.BaseMainSlot.calculateHeight();
          this.$refs.tableData.setCurrentRow();
          this.$refs.tableData.clearSelection();
        });
      } else if (this.topitemtypeId === "TEMPLATE") {
        this.tableColumnsData = this.tableLabel_Temp;
        this.$nextTick(() => {
          this.$refs.BaseMainSlot.calculateHeight();
          this.$refs.tableData.setCurrentRow();
          this.$refs.tableData.clearSelection();
        });
      }
      this.bFirstLoad = false;
      // 获取表格数据
      this.queryPageList();
    },
    queryPageList(e) {
      if (this.topitemtypeId === "CONFIG") {
        this.queryConfigPageList(e);
      }
      if (this.topitemtypeId === "TEMPLATE") {
        this.queryTemplatePageList(e);
      }
    },
    // 设备保养项配置
    queryConfigPageList(e) {
      this.loading = false;
      // 获取数据
      let param = {
        page: this.currentPage,
        size: this.pageSize,
        // equipmentCode: this.nowEquipObject.equipmentCode
      };
      let condition = [
        {
          paramName: "equipmentCode",
          value: this.nowEquipObject.equipmentCode,
          sign: "equals",
        },
      ];
      if (e?.checkItemName) {
        condition.push({
          paramName: "checkItemName",
          value: e.checkItemName,
          sign: "like",
        });
      }
      if (e?.checkItemContent) {
        condition.push({
          paramName: "checkItemContent",
          value: e.checkItemContent,
          sign: "like",
        });
      }
      if (e?.accessMethod) {
        condition.push({
          paramName: "accessMethod",
          value: e.accessMethod,
          sign: "like",
        });
      }
      if (sessionStorage.farming) {
        condition.push({
          paramName: "farming",
          value: sessionStorage.farming,
          sign: "equals",
        });
      }
      console.log(condition);
      param["condition"] = encodeURI(JSON.stringify(condition));
      maintenanceDataitemApi.queryConfigPageList(param).then((res) => {
        this.loading = false;
        if (res.code === 1) {
          let data = res.data;
          this.totalSize = data.total;
          this.tableData = data.list;
          this.addblankmet();
          this.resetActionBar();
        }
      });
    },
    // 保养项模板配置
    queryTemplatePageList(e) {
      this.loading = false;
      // 获取数据
      let param = {
        page: this.currentPage,
        size: this.pageSize,
      };
      // if (e) {
        let condition = [];
        if (e?.checkItemName) {
          condition.push({
            paramName: "checkItemName",
            value: e.checkItemName,
            sign: "like",
          });
        }
        if (e?.checkType) {
          condition.push({
            paramName: "checkType",
            value: e.checkType,
            sign: "equals",
          });
        }
        if (e?.accessMethod) {
          condition.push({
            paramName: "accessMethod",
            value: e.accessMethod,
            sign: "like",
          });
        }
        if (sessionStorage.farming) {
          condition.push({
            paramName: "farming",
            value: sessionStorage.farming,
            sign: "equals",
          });
      }
        param["condition"] = encodeURI(JSON.stringify(condition));
      // }

      maintenanceDataitemApi.queryTemplatePageList(param).then((res) => {
        this.loading = false;
        if (res.code === 1) {
          let data = res.data;
          this.totalSize = data.total;
          this.tableData = data.list;
          let havline = this.tableData.length % this.pageSize;
          if (this.tableData.length < this.pageSize) {
            if (havline < this.pageSize) {
              const remain = this.pageSize - havline;
              for (var i = 0; i < remain; i++) {
                this.tableData.push({
                  index: i + this.tableData.length - 1,
                });
              }
            }
          }
          this.resetActionBar();
        }
      });
    },
    handleSelectionChange(list) {
      if (list.length == 0) {
        this.delActive = false;
        return;
      }

      this.checkedIdList = [];
      let emptyList = [];
      console.log(this.topitemtypeId, list);
      list.forEach((item) => {
        if (this.topitemtypeId === "CONFIG") {
          if (item.equipmentCheckItemMapperId) {
            this.checkedIdList.push(item.equipmentCheckItemMapperId);
          } else {
            emptyList.push(item);
          }
        } else {
          if (item.checkItemModelId) {
            this.checkedIdList.push(item.checkItemModelId);
          } else {
            emptyList.push(item);
          }
        }
      });
      if (this.checkedIdList.length >= 1) {
        this.delActive = true;
      } else {
        this.delActive = false;
        this.$message.warning("不可选择空数据！");
      }
      if (list.length === emptyList.length) {
        this.toggleNoSelection();
      } else {
        this.toggleNoSelection(emptyList);
      }
    },
    // 单个删除
    delOne(data) {
      this.$confirm("此操作将永久删除该项, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass",
      })
        .then(() => {
          if (this.topitemtypeId === "CONFIG") {
            maintenanceDataitemApi
              .delList({
                equipmentCheckItemMapperIdList: [
                  data.equipmentCheckItemMapperId,
                ],
              })
              .then((res) => {
                if (res.code === 1) {
                  this.$message.success(res.msg);
                  this.queryPageList();
                  this.resetActionBar();
                }
              });
          }
          if (this.topitemtypeId === "TEMPLATE") {
            maintenanceDataitemApi
              .delTempalteList({
                checkItemModelIdList: [data.checkItemModelId],
              })
              .then((res) => {
                if (res.code === 1) {
                  this.$message.success(res.msg);
                  this.queryPageList();
                  this.resetActionBar();
                }
              });
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 表格删除
    delmessage() {
      if (this.topitemtypeId === "CONFIG") {
        maintenanceDataitemApi
          .delList({ equipmentCheckItemMapperIdList: this.checkedIdList })
          .then((res) => {
            if (res.code === 1) {
              this.$message.success(res.msg);
              this.queryPageList();
              this.resetActionBar();
            }
          });
      }
      if (this.topitemtypeId === "TEMPLATE") {
        maintenanceDataitemApi
          .delTempalteList({ checkItemModelIdList: this.checkedIdList })
          .then((res) => {
            if (res.code === 1) {
              this.$message.success(res.msg);
              this.queryPageList();
              this.resetActionBar();
            }
          });
      }
    },
    // 添加
    add() {
      this.nowChanceStau = "add";
      this.titleText = "添加";
      this.addActive = false;
      this.delActive = false;
      if (this.topitemtypeId === "CONFIG") {
        this.showAddEditConfigDialog = true;
      }
      if (this.topitemtypeId === "TEMPLATE") {
        this.showAddEditTemplateDialog = true;
      }
    },
    // 修改
    edit(row) {
      if (this.topitemtypeId === "CONFIG") {
        this.editObject = JSON.parse(JSON.stringify(row));
        this.nowChanceStau = "edit";
        this.titleText = "修改";
        this.addActive = false;
        this.delActive = false;
        this.showAddEditConfigDialog = true;
      } else if (this.topitemtypeId === "TEMPLATE") {
        this.editObject = JSON.parse(JSON.stringify(row));
        this.nowChanceStau = "edit";
        this.titleText = "修改";
        this.addActive = false;
        this.delActive = false;
        this.showAddEditTemplateDialog = true;
      }
    },
    closeDialog() {
      this.showAddEditConfigDialog = false;
      this.showAddEditTemplateDialog = false;
      this.nowChanceStau = "";
      this.titleText = "";
      this.editObject = {};
      this.addActive = true;
      this.delActive = false;

      this.$refs.tableData.setCurrentRow();
      this.$refs.tableData.clearSelection();
      this.queryPageList();
    },
    cancel() {
      this.showAddEditConfigDialog = false;
      this.showAddEditTemplateDialog = false;
      this.nowChanceStau = "";
      this.titleText = "";
      this.editObject = {};
      this.addActive = true;
      this.delActive = false;

      this.$refs.tableData.setCurrentRow();
      this.$refs.tableData.clearSelection();
    },
  },
};
</script>

<style lang="scss" scoped>
.check-item-con {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  overflow-y: auto;
  padding: 0 0 20px 0;
  .tr-sid {
    width: 250px;
    height: 100%;
    padding: 10px;
    margin-right: 20px;
    background-color: #225768;
    .sid-head {
      width: 100%;
      height: 40px;
      line-height: 40px;
      font-size: 17px;
      text-align: center;
      border-bottom: #fff dashed 1px;
    }
    .sid-tree {
      width: 100%;
      height: calc(100% - 40px);
      overflow-y: auto;
    }
  }
  .table-box {
    width: calc(100% - 270px);
    height: 100%;
  }
  .table-box-all {
    width: 100%;
    height: 100%;
  }
}

::v-deep .table {
  padding: 10px 0 10px;
}
</style>
